package com.synergy.stockflow.production.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.synergy.stockflow.model.Result;
import com.synergy.stockflow.product.entity.ProcessStep;
import com.synergy.stockflow.product.service.ProcessDetailService;
import com.synergy.stockflow.product.service.ProcessStepService;
import com.synergy.stockflow.production.create.ProductionPlanDetailDTO;
import com.synergy.stockflow.production.entity.ProductionPlan;
import com.synergy.stockflow.production.entity.ProductionPlanDetail;
import com.synergy.stockflow.production.service.ProductionPlanDetailService;
import com.synergy.stockflow.production.service.ProductionPlanService;
import com.synergy.stockflow.production.service.ProductionTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/production/plan")//生产管理
public class ProductionPlanController {

    //注入生产计划服务
    @Autowired
    private ProductionPlanService productionPlanService;

    @Autowired
    private ProductionPlanDetailService productionPlanDetailService;

    @Autowired
    private ProductionTaskService productionTaskService;

    @Autowired
    private ProcessDetailService processDetailService;

    @Autowired
    private ProcessStepService processStepService;

    //查询所有计划主表数据
    @GetMapping("/page")
    public Result<Page<ProductionPlan>> list(
            @RequestParam(name = "current", defaultValue = "1") int current,
            @RequestParam(name = "size", defaultValue = "2") int size,
            @RequestParam(name="planCode",required = false) String planCode,
            @RequestParam(name="planName",required = false) String planName,
            @RequestParam(name="palnType",required = false) Integer planType,
            @RequestParam(name="salesOrderId",required = false) String salesOrderId,
            @RequestParam(name="planStatus",required = false) Integer planStatus,
            @RequestParam(name="startDate",required = false) String startDate,
            @RequestParam(name="endDate",required = false) String endDate
    ) {
        QueryWrapper<ProductionPlan> queryWrapper = new QueryWrapper<>();
        if(planCode != null){
            queryWrapper.lambda().eq(ProductionPlan::getPlanCode,planCode);
        }
        if(planName != null){
            queryWrapper.lambda().like(ProductionPlan::getPlanName,planName);
        }
        if(planType != null){
            queryWrapper.lambda().eq(ProductionPlan::getPlanType,planType);
        }
        if(salesOrderId != null){
            queryWrapper.lambda().eq(ProductionPlan::getSalesOrderId,salesOrderId);
        }
        if(planStatus != null){
            queryWrapper.lambda().eq(ProductionPlan::getPlanStatus,planStatus);
        }
        if(startDate != null){
            queryWrapper.lambda().ge(ProductionPlan::getStartDate,startDate);
        }
        if(endDate != null){
            queryWrapper.lambda().le(ProductionPlan::getEndDate,endDate);
        }
        queryWrapper.orderByDesc("plan_id");
        Page<ProductionPlan> objectPage = new Page<>(current, size);
        productionPlanService.page(objectPage, queryWrapper);
        return Result.success(objectPage);
    }

    //查询单条计划明细表数据（根据明细ID查）
    @GetMapping("/detail")
    public Result<ProductionPlanDetail> getDetail(@RequestParam("detail_Id") String detailId) {
        ProductionPlanDetail productionPlanDetail = productionPlanDetailService.getById(detailId);
        System.out.println(detailId);
        if (productionPlanDetail == null) {

            return Result.error(404, "未找到对应的数据", null);
        }
        return Result.success(productionPlanDetail);
    }

    @GetMapping("/detailByPlanCode")
    public Result<List<ProductionPlanDetailDTO>> getDetailByPlanCode(@RequestParam("planCode") String planCode) {
        List<ProductionPlanDetailDTO> productionPlanDetailDTOS = productionPlanDetailService.selectByPlanCode(planCode);
        return Result.success(productionPlanDetailDTOS);
    }


    //添加生产计划主表数据
    @PostMapping("/insert")
    public Result insert(@RequestBody ProductionPlan productionPlan) {
        productionPlan.setPlanCode(generatePlanCode());
        productionPlan.setPlanStatus(1);
        productionPlan.setStartDate(new Date());
        productionPlan.setEndDate(new Date());
        productionPlan.setManagerId("1");
        productionPlan.setCreateTime(new Date());
        productionPlan.setUpdateTime(new Date());
        productionPlanService.save(productionPlan);//保存主表数据

          productionPlan.getProductionPlanDetails().setPlanId(productionPlan.getPlanId());
        productionPlan.getProductionPlanDetails().setActualQuantity(BigDecimal.valueOf(0));
        productionPlan.getProductionPlanDetails().setCompletedQuantity(BigDecimal.valueOf(0));
        productionPlan.getProductionPlanDetails().setStatus(0);
        productionPlan.getProductionPlanDetails().setCreateTime(new Date());
        productionPlan.getProductionPlanDetails().setUpdateTime(new Date());
        productionPlanDetailService.save(productionPlan.getProductionPlanDetails());//保存详情表数据

//        根据详情表的工艺路线查工序ID
//        productionPlan.getProductionPlanDetails().forEach(item -> {
//                    List<ProcessDetail> processList = processDetailService.list(new QueryWrapper<ProcessDetail>().eq("process_route_id", item.getRoutingId()));
//                    processList.forEach(process -> {
//                        ProductionTask productionTask = new ProductionTask();
//                        productionTask.setPlanId(productionPlan.getPlanId());
//                        productionTask.setDetailId(item.getDetailId());
//                        productionTask.setOperationId(process.getProcessId());
//                        productionTask.setStatus(0);
//                        productionTask.setStartDate(productionPlan.getStartDate());
//                        productionTask.setEndDate(productionPlan.getEndDate());
//                        productionTask.setAssignedQuantity(item.getPlanQuantity());
//                        productionTask.setCompletedQuantity(item.getCompletedQuantity());
//                        productionTask.setTeamId(getTeamIdByProcessId(process.getProcessId()));
//                        productionTask.setQualityStatus(0);
//                        productionTask.setCreateTime(new Date());
//                        productionTask.setUpdateTime(new Date());
//                        productionTaskService.save(productionTask);//保存生产任务
//                    });
//                });
        return Result.success(productionPlan);
    }
    //根据工序Id,查询生产班组
    private String getTeamIdByProcessId(String processId) {
        ProcessStep byId = processStepService.getById(processId);
        return byId.getTeam();
    }

    // 生成计划编号的方法 (格式:PP-202407001)
    private String generatePlanCode() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        String dateStr = sdf.format(new Date());

        // 查询当月的计划数量
        int count = productionPlanService.countCurrentMonthPlans();

        return "PP-" + dateStr + String.format("%03d", count + 1);
    }

    //修改
    @PutMapping("/update")
    public Result update(@RequestBody ProductionPlan productionPlan) {
        productionPlan.setUpdateTime(new Date());
        productionPlanService.updateById(productionPlan);
        return Result.success(productionPlan);
    }

    //删除(修改状态）
    @PutMapping("/delete")
    public Result completeProductionPlan(@RequestParam("planId") String planId) {
        ProductionPlan byId = productionPlanService.getById(planId);
        if (byId != null && 1==(byId.getPlanStatus())) {
            byId.setPlanStatus(4);  // 注意：状态应该是字符串
            byId.setUpdateTime(new Date());
            productionPlanService.updateById(byId);  // 需要保存修改
            return Result.success("计划已删除");
        } else {
            return Result.error(404, "该计划无法删除");
        }
    }

    //根据计划Id查详情
    @GetMapping("/getByPlanId")
    public Result getByPlanId(@RequestParam("planId") String planId) {
        return Result.success(productionPlanDetailService.selectByPlanId(planId));
    }

    @GetMapping("/selectBom")
    public Result selectBom(String planId) {
        ProductionPlan productionPlan = productionPlanService.selectBom(planId);
        return Result.success(productionPlan);
    }




}
